package com.sm.service;

import com.sm.ali.alipay.AliPay;
import com.sm.bo.VipOrderBO;
import com.sm.dao.UserVipOrderMapper;
import com.sm.model.UserVipOrder;
import com.sm.util.CommonUtil;
import com.sm.util.UUIDUtils;
import com.sm.wx.vo.AjaxResult;
import com.sm.wx.vo.WxOrderVO;
import com.sm.wx.wxpay.WxPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.stream.Collectors;

@Service
public class UserVipOrderService {

    @Autowired
    private UserVipOrderMapper userVipOrderMapper;

    @Autowired
    private WxPay wxPay;

    @Autowired
    private AliPay aliPay;

    /**
     * 创建VIP订单
     *
     * @param vipOrder
     */
    @Transactional
    public AjaxResult createVipOrder(HttpServletRequest request, VipOrderBO vipOrder) {

        //支付类型 1支付宝2微信
        Integer payType = vipOrder.getPayType();
        //创建订单
        UserVipOrder userVipOrder = new UserVipOrder();
        userVipOrder.setUserId(vipOrder.getUserId());
        userVipOrder.setPrice(vipOrder.getPrice());
        userVipOrder.setCreateTime(new Date());
        userVipOrder.setIsPay(0);
        userVipOrder.setOrderNum("Y" + CommonUtil.getOutTradeNo());
        userVipOrder.setPayType(vipOrder.getPayType());
        String vipIds = String.join(",", vipOrder.getVipIdStrs());
        userVipOrder.setVipId(vipIds);
        userVipOrderMapper.insert(userVipOrder);
        if (payType == 2) {
            WxOrderVO wxOrderVO = new WxOrderVO("VIP订单", "1", userVipOrder.getOrderNum(), userVipOrder.getPrice().multiply(new BigDecimal("100")).intValue()+"", "vipOrderNotify.do");
            //微信支付
            return wxPay.appPay(request, wxOrderVO);
        } else if (vipOrder.getPayType() == 1) {
            WxOrderVO wxOrderVO = new WxOrderVO("VIP订单", "1", userVipOrder.getOrderNum(), userVipOrder.getPrice(), "aliVipOrderNotify.do");
            return aliPay.appPay(wxOrderVO);
        } else {
            return new AjaxResult().addError("支付失败");
        }
    }

    /**
     * 获取VIP订单状态
     * @param orderNum
     * @return
     */
    public Integer getVipOrderStatus(String orderNum) {
        UserVipOrder userVipOrder = userVipOrderMapper.selectByOrderNum(orderNum);
        if (userVipOrder == null) {
            return -1;
        } else {
            return userVipOrder.getIsPay();
        }
    }
}
